import time

class ModuleImportTester:
    def __init__(self):
        # 存储模块信息的列表，格式: (模块名称, 导入语句)
        self.modules = []
        
    def add_module(self, name, import_stmt):
        """添加模块到测试列表"""
        self.modules.append((name, import_stmt))
        
    def add_modules_from_list(self, module_list):
        """从列表批量添加模块"""
        self.modules.extend(module_list)
        
    def test_imports(self):
        """测试所有模块的导入时间"""
        import_times = []
        total_start = time.time()
        
        # 打印表头
        print(f"{'模块名称':<40} {'状态':<10} {'耗时(毫秒)':<15}")
        print("-" * 70)
        
        for name, import_stmt in self.modules:
            start_time = time.time()
            try:
                # 执行导入语句
                exec(import_stmt)
                end_time = time.time()
                duration = (end_time - start_time) * 1000  # 转换为毫秒
                import_times.append((name, duration))
                print(f"{name:<40} 成功      {duration:.2f}")
            except ImportError as e:
                print(f"{name:<40} 缺失      -         错误: {str(e)[:30]}...")
            except Exception as e:
                print(f"{name:<40} 错误      -         错误: {str(e)[:30]}...")
        
        total_duration = (time.time() - total_start) * 1000  # 总耗时
        return import_times, total_duration
    
    def display_results(self, import_times, total_duration):
        """展示测试结果"""
        print("\n" + "=" * 70)
        print(f"总导入时间: {total_duration:.2f} 毫秒")
        print("=" * 70)
        print("各模块导入时间（从长到短）:")
        print(f"{'排名':<5} {'模块名称':<40} {'耗时(毫秒)':<15}")
        print("-" * 65)
        
        # 按耗时排序
        sorted_times = sorted(import_times, key=lambda x: x[1], reverse=True)
        
        for i, (name, duration) in enumerate(sorted_times, 1):
            print(f"{i:<5} {name:<40} {duration:.2f}")

if __name__ == "__main__":
    # 创建测试器实例
    tester = ModuleImportTester()
    
    # 1. 标准库模块 - 在这里添加新的标准库模块
    standard_libs = [
        ('threading', 'import threading'),
        ('yaml', 'import yaml'),
        ('json', 'import json'),
        ('datetime', 'import datetime'),
        ('pathlib', 'import pathlib'),
        ('time', 'import time'),
        ('shutil', 'import shutil'),
        ('subprocess', 'import subprocess'),
        ('os', 'import os'),
        ('sys', 'import sys'),
        ('re', 'import re'),
        ('requests', 'import requests'),
        ('psutil', 'import psutil'),
        ('ctypes', 'import ctypes'),
        ('typing', 'import typing'),
        ('configparser', 'import configparser'),
        ('zipfile', 'import zipfile'),
        ('sqlite3', 'import sqlite3'),
        ('random', 'import random'),
        ('logging', 'import logging'),
        # 示例：添加新模块只需在这里加一行
        # ('新模块名', 'import 新模块名'),
    ]
    tester.add_modules_from_list(standard_libs)
    
    # 2. Selenium相关模块 - 在这里添加新的Selenium模块
    selenium_modules = [
        ('selenium.webdriver.edge.webdriver', 'from selenium.webdriver.edge.webdriver import WebDriver'),
        ('selenium.webdriver.common.action_chains', 'from selenium.webdriver.common.action_chains import ActionChains'),
        ('selenium.webdriver.support.ui', 'from selenium.webdriver.support.ui import WebDriverWait'),
        ('selenium.webdriver.edge.service', 'from selenium.webdriver.edge.service import Service'),
        ('selenium.webdriver.edge.options', 'from selenium.webdriver.edge.options import Options'),
        ('selenium.webdriver.remote.webelement', 'from selenium.webdriver.remote.webelement import WebElement'),
        ('selenium.webdriver.common.keys', 'from selenium.webdriver.common.keys import Keys'),
        ('selenium.webdriver.common.by', 'from selenium.webdriver.common.by import By'),
        ('selenium.webdriver.support', 'from selenium.webdriver.support import expected_conditions'),
        ('selenium.common.exceptions', 'from selenium.common.exceptions import *'),
        # 示例：添加新的Selenium模块
        # ('selenium.新模块路径', 'from selenium.新模块路径 import 类名'),
    ]
    tester.add_modules_from_list(selenium_modules)
    
    # 3. PySide6相关模块 - 在这里添加新的PySide6模块
    pyside6_modules = [
        ('PySide6.QtWidgets', 'from PySide6.QtWidgets import (QWidget, QMainWindow, QDialog, QFileDialog, QMessageBox, QPushButton, QListView, QListWidget, QListWidgetItem, QLineEdit, QTextEdit, QLabel, QHeaderView, QInputDialog, QApplication, QProgressBar, QComboBox)'),
        ('PySide6.QtCore', 'from PySide6.QtCore import (Qt, QCoreApplication, QObject, QMetaObject, Signal, Slot, QDateTime, QThread, QThreadPool, QTimer, QTemporaryFile, QTemporaryDir, QJsonArray, QJsonDocument, QJsonParseError, QJsonValue, QFile, QFileDevice, QIODevice, QIODeviceBase, QFileInfo, QTextStream, QStringListModel, QModelIndex)'),
        # 示例：添加新的PySide6模块
        # ('PySide6.新模块', 'from PySide6.新模块 import 类名'),
    ]
    tester.add_modules_from_list(pyside6_modules)
    
    # 4. 图像相关模块
    image_modules = [
        ('PIL', 'import PIL'),
        ('cv2', 'import cv2'),
        # 可以在这里继续添加其他图像相关模块
    ]
    tester.add_modules_from_list(image_modules)
    
    # 5. 单独添加其他模块（如果需要）
    # tester.add_module('模块名', 'import 模块名')
    tester.add_module('pandas','import pandas')
    tester.add_module('numpy','import numpy')
    
    # 执行测试
    import_times, total_duration = tester.test_imports()
    
    # 展示结果
    tester.display_results(import_times, total_duration)
    